import React, { useState, useEffect } from "react";
import { _getData } from "./Api";
import "./Summary_data.css";
import { Spin } from "antd";
import { Pie } from 'react-chartjs-2';

const Summary_data = () => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true); // 初始化加载状态
  const [chartData1, setChartData1] = useState({});
  const [chartData2, setChartData2] = useState({});

  useEffect(() => {
    const dataReq = async () => {
      try {
        const res = await _getData();

        setData(res);
        setLoading(false);

        // 数据获取后，更新饼状图数据
        setChartData1({
          labels: ['待发货', '配送中', '待退款', '已退款', '已成交'],
          datasets: [{
            data: [res.sendPercent, res.deliveryPercent, res.refundPercent, res.haveRefundPercent, res.haveDealPercent],
            backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF'],
            hoverBackgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF']
          }]
        });

        setChartData2({
          labels: ['总成交数', '总失败数'],
          datasets: [{
            data: [res.totalDeal, res.totalFalse],
            backgroundColor: ['#FF6384', '#36A2EB'],
            hoverBackgroundColor: ['#FF6384', '#36A2EB']
          }]
        });
      } catch (err) {
        console.log("error:", err);
        setLoading(false);
      }
    };
    dataReq();
  }, []);

  if (loading) {
    return <Spin />;
  }

  return (
    <>
      <table>
        <tr className="leftTR">
          <th>今日新增:{data.today}元</th>
          <th>待发货</th>
          <th>配送中</th>
          <th>待退款</th>
          <th>已退款</th>
          <th>已成交</th>
        </tr>
        <tr className="leftTR">
          <td>总销售额：</td>
          <td>累计数量：</td>
          <td>累计数量：</td>
          <td>累计数量：</td>
          <td>累计数量：</td>
          <td>累计数量：</td>
        </tr>
        <tr className="rightTR">
          <td>
            <h3>{data.totalSales}元</h3>
          </td>
          <td>
            <h3>{data.send}</h3>
          </td>
          <td>
            <h3>{data.delivery}</h3>
          </td>
          <td>
            <h3>{data.refund}</h3>
          </td>
          <td>
            <h3>{data.haveRefund}</h3>
          </td>
          <td>
            <h3>{data.haveDeal}</h3>
          </td>
        </tr>
      </table>

      <div className="pies">
        <div className="pie1">
          <center><h2>订单状态比率</h2></center>
          <Pie data={chartData1} />
        </div>
        <div className="pie2">
        <center><h2>订单成败比率</h2></center>
          <Pie data={chartData2} />
        </div>
      </div>
    </>
  );
};

export default Summary_data;